package com.zsc.newbuds.controller;

import com.zsc.newbuds.service.impl.SendSmsImpl;
import com.zsc.newbuds.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.UUID;

/**阿里云接口调用
 * @author D
 */
@Controller
//跨域支持
@CrossOrigin
public class SmsApiController {

    @Autowired
    private SendSmsImpl sendSms;

    @Autowired
    private RedisUtil redisUtil;

    @ResponseBody
    @GetMapping("/send")
    public Object code(String phone){

        int flag = 1;
        System.out.println("手机号"+phone);

        //判断redis是否有验证码
        String code = (String)redisUtil.get(phone);

        if(!StringUtils.isEmpty(code)){
            return code;
        }

        code = UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> param = new HashMap<>();
        param.put("code",code);
        boolean isSend = sendSms.send(phone,"SMS_204287067",param);

        if(isSend){
            redisUtil.set(phone,code);
            redisUtil.expire(phone,3000);
        }else {
            //发送失败
            flag = 0;

        }
        return flag;

    }
}
